//
//  MACFilterVC.swift
//  MIFI
//
//  Created by 金嗓子卡卡 on 2019/5/4.
//  Copyright © 2019 NJMifi. All rights reserved.
//

import UIKit
import SVProgressHUD
class MACFilterVC: RootVC {

    enum Mode : Int {
        case noRules
        case whiteList
        case blackList
    }
    
    private let modes = ["No rules ▼","Whitelist ▼","Blacklist ▼"]
    private var blackDatas : [String] = []
    private var whiteDatas : [String] = []
    private var aclMode = ""
    private var mode = Mode.noRules {
        didSet {
            modeBtn.setTitle(modes[mode.rawValue], for: .normal)
            addBtn.isEnabled = mode != .noRules
            let color = addBtn.isEnabled ? blackColor : colorRGBA(red: 200, green: 200, blue: 200, alpha: 1)
            addBtn.setTitleColor(color, for: .normal)
            tableView.reloadData()
        }
    }
    
    private lazy var modeTitleLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 16, y: naviView!.bottom, width: (screenWidth - 16 * 2) * 2 / 3, height: 50))
        label.backgroundColor = clearColor
        label.textColor = blackColor
        label.text = "MAC filtering rules"
        label.font = UIFont.systemFont(ofSize: 22)
        return label
    }()
    
    private lazy var modeBtn: UIButton = {
        let btn = UIButton(frame: CGRect(x: modeTitleLabel.right, y: modeTitleLabel.top, width: modeTitleLabel.width / 2, height: modeTitleLabel.height))
        btn.setTitle("No rules ▼", for: .normal)
        btn.backgroundColor = clearColor
        btn.addTarget(self, action: #selector(changeMode), for: .touchUpInside)
        btn.setTitleColor(blackColor, for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        return btn
    }()
    
    private lazy var addBtn: UIButton = {
        let btn = UIButton(frame: CGRect(x: 24, y: modeTitleLabel.bottom, width: screenWidth - 24 * 2, height: 40))
        btn.backgroundColor = colorRGBA(red: 220, green: 220, blue: 220, alpha: 1)
        btn.setTitleColor(colorRGBA(red: 200, green: 200, blue: 200, alpha: 1), for: .normal)
        btn.setTitle("ADD", for: .normal)
        btn.layer.shadowOffset = CGSize(width: 1, height: 1)
        btn.layer.shadowColor = blackColor.cgColor
        btn.layer.shadowOpacity = 0.5
        btn.layer.shadowRadius = 4
        btn.isEnabled = false
        btn.addTarget(self, action: #selector(addMacAddress), for: .touchUpInside)
        return btn
    }()
    
    private lazy var tableView: UITableView = {
        let tab = UITableView(frame: CGRect(x: 0, y: addBtn.bottom + 8, width: screenWidth, height: screenHeight - addBtn.bottom - 8), style: .grouped)
        tab.backgroundColor = whiteColor
        tab.rowHeight = 60
        tab.delegate = self
        tab.dataSource = self
        tab.separatorStyle = .none
        tab.register(MacListCell.self, forCellReuseIdentifier: "cell")
        
        let gestureRec:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressToDo))
        gestureRec.minimumPressDuration = 1
        
        tab.addGestureRecognizer(gestureRec)
        return tab
    }()
    @objc func longPressToDo(gesture:UILongPressGestureRecognizer){
        
        if gesture.state == .began {
            
            let point = gesture.location(in: self.tableView)
            
            let indexPath = self.tableView.indexPathForRow(at: point)
            
            
            if indexPath!.isEmpty {
                return
                
            }
            
            let alertVC = UIAlertController(title: "Alert", message: "Are you sure you want to delete this configuration?", preferredStyle: .alert)
            
            let action2 = UIAlertAction(title: "Cancel", style: .default) { (action) in
                
            }
            alertVC.addAction(action2)
            let action = UIAlertAction(title: "OK", style: .default) { (action) in
                
                
                switch self.mode {
                case .noRules:
                    self.aclMode = "0"
                case .whiteList:
                    self.aclMode = "1"
                    self.whiteDatas.remove(at: indexPath!.row)
                case .blackList:
                    self.aclMode = "2"
                    self.blackDatas.remove(at: indexPath!.row)
                }
                var whiteList = ""
                var blackList = ""
                if self.whiteDatas.count > 0 {
                    for str in self.whiteDatas {
                        whiteList = whiteList + str + ";"
                    }
                    whiteList.removeLast()
                }
                if self.blackDatas.count > 0 {
                    for str in self.blackDatas {
                        blackList = blackList + str + ";"
                    }
                    blackList.removeLast()
                }
                net_setACLMode(aclmode: self.aclMode, blackList: blackList, whiteList: whiteList) { [weak self] (success) in
                    if success {
                        self?.tableView.reloadData()
                    }
                }
            }
            
                
            
            alertVC.addAction(action)
            self.present(alertVC, animated: true, completion: nil)
            
            
            
            
            
        }
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        getData()
    }
    
    override func configView() {
        configNaviView(title: "Wireless MAC Filter")
        rightBtn?.backgroundColor = clearColor
        rightBtn?.setTitle("OK", for: .normal)
        rightBtn?.setTitleColor(whiteColor, for: .normal)
        rightBtn?.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        view.backgroundColor = whiteColor
        
        view.addSubview(modeTitleLabel)
        view.addSubview(modeBtn)
        view.addSubview(addBtn)
        view.addSubview(tableView)
    }
    
    @objc private func changeMode() {
        let sheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        for (index,string) in modes.enumerated() {
            let action = UIAlertAction(title: string[0..<string.count-2], style: .default) {[weak self] (action) in
                self?.mode = Mode.init(rawValue: index)!
            }
            sheet.addAction(action)
        }
        let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        sheet.addAction(cancel)
        present(sheet, animated: true, completion: nil)
    }
    
    @objc private func addMacAddress() {
        let alertView = InputAlertView(input: "",content: "Please enter the MAC")
        alertView.handle = ({[weak self] content in
            self?.addMac(mac: content)
        })
        let alertVC = CustomAlertVC(contentType: .animation(alertView))
        alertVC.show()
    }
    
    private func addMac(mac:String) {
        guard mac.isMacAddress() else {
            SVProgressHUD.showError(withStatus: "Please enter the correct MAC")
            return
        }
        switch mode {
        case .whiteList:
            whiteDatas.append(mac)
            aclMode = "1"
        case .blackList:
            blackDatas.append(mac)
            aclMode = "2"
        default:
            break
        }
    
    
        var whiteList = ""
        var blackList = ""
        if whiteDatas.count > 0 {
            for str in whiteDatas {
                whiteList = whiteList + str + ";"
            }
            whiteList.removeLast()
        }
        if blackDatas.count > 0 {
            for str in blackDatas {
                blackList = blackList + str + ";"
            }
            blackList.removeLast()
        }
        net_setACLMode(aclmode: aclMode, blackList: blackList, whiteList: whiteList) { [weak self] (success) in
            
            if success {
                self!.tableView.reloadData()
            }else{
                
                switch self!.mode {
                case .whiteList:
                    self!.whiteDatas.removeLast()
                case .blackList:
                    self!.blackDatas.removeLast()
                default:
                    break
                }
                
                 SVProgressHUD.showError(withStatus: "Please enter the correct MAC")
            }
            
        }
        
        
    }
    
    private func getData() {
        net_getACLMode {[weak self] (model) in
            if model != nil {
                if model?.ACL_mode != nil {
                    self?.aclMode = model!.ACL_mode!
                    if Int(model!.ACL_mode!) != nil{
                        self?.mode = Mode.init(rawValue: Int(model!.ACL_mode!)!)!
                    }
                }
                self?.getListModel(model: model!)
            }
            self?.tableView.reloadData()
        }
    }
    
    private func getListModel(model:MacAddressListModel) {
        if !isEmpty(string: model.wifi_mac_black_list) {
            blackDatas = model.wifi_mac_black_list!.components(separatedBy: ";")
        }
        if !isEmpty(string: model.wifi_mac_white_list) {
            whiteDatas = model.wifi_mac_white_list!.components(separatedBy: ";")
        }
    }
    
    override func rightBtnClicked(sender: UIButton) {
        
        switch mode {
        case .noRules:
            aclMode = "0"
        case .whiteList:
            aclMode = "1"
        case .blackList:
            aclMode = "2"
        default:
            break
        }
        var whiteList = ""
        var blackList = ""
        if whiteDatas.count > 0 {
            for str in whiteDatas {
                whiteList = whiteList + str + ";"
            }
            whiteList.removeLast()
        }
        if blackDatas.count > 0 {
            for str in blackDatas {
                blackList = blackList + str + ";"
            }
            blackList.removeLast()
        }
        net_setACLMode(aclmode: aclMode, blackList: blackList, whiteList: whiteList) { [weak self] (success) in
            if success {
                self?.navigationController?.popViewController(animated: true)
            }
        }
    }
    
}

extension MACFilterVC : UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch mode {
        case .blackList:
            return blackDatas.count
        case .whiteList:
            return whiteDatas.count
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MacListCell
        
        var data : [String] = []
        switch mode {
        case .blackList:
            data = blackDatas
        case .whiteList:
            data = whiteDatas
        default:
            break
        }
        cell.refresh(mac: data[indexPath.row])
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
}

fileprivate class MacListCell : UITableViewCell {
    private lazy var imageV: UIImageView = {
        let imageV = UIImageView(frame: CGRect(x: 12, y: 10, width: 40, height: 40))
        imageV.image = #imageLiteral(resourceName: "device").withRenderingMode(.alwaysTemplate)
        imageV.tintColor = blackColor
        return imageV
    }()
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: imageV.right + imageV.left, y: 0, width: screenWidth - imageV.right - imageV.left * 2, height: 60))
        label.backgroundColor = clearColor
        label.text = "MAC Address:"
        label.textColor = blackColor
        label.font = UIFont.systemFont(ofSize: 19)
        return label
    }()
    
    private lazy var line: UIView = {
        let line = UIView(frame: CGRect(x: 8, y: 60 - 0.5, width: screenWidth - 16, height: 0.5))
        line.backgroundColor = textGray
        return line
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        configView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func configView() {
        selectionStyle = .none
        contentView.addSubview(imageV)
        contentView.addSubview(titleLabel)
        contentView.addSubview(line)
    }
    
    func refresh(mac:String) {
        titleLabel.text = "MAC Address: " + mac
    }
}
